#pragma once

#include <iostream>
#include <memory>
#include <string>
#include <random>
#include <unistd.h>
#include <ctime>
#include <sys/types.h>
#include <stdlib.h>
#include <jsoncpp/json/json.h>

#define SELFDEFINE 1;

namespace protocol_ns
{
    const std::string SEP = "\r\n";

    // 解决粘包问题
    std::string Encode(const std::string &json_str)
    {
        int json_str_len = json_str.size();
        std::string proto_str = std::to_string(json_str_len);
        proto_str += SEP;
        proto_str += json_str;
        proto_str += SEP;

        return proto_str;
    }
    std::string Decode(std::string &inbuffer)
    {
        auto pos = inbuffer.find(SEP);
        if (pos == std::string::npos)
            return std::string("");

        std::string str_len = inbuffer.substr(0, pos);
        if (str_len.empty())
            return std::string("");
        int packlen = std::stoi(str_len);

        int total = packlen + str_len.size() + SEP.size() * 2;
        if (inbuffer.size() < total)
            return std::string("");

        std::string package = inbuffer.substr(pos + SEP.size(), packlen);
        inbuffer.erase(0, total);
        return package;
    }

    class Request
    {
    public:
        Request()
        {
        }
        Request(int x, int y, char oper)
            : _x(x), _y(y), _oper(oper)
        {
        }
        bool Serialize(std::string *out)
        {
#ifdef SELFDEFINE
            *out = std::to_string(_x) + SEP + _oper + SEP + std::to_string(_y);
            return true; 
#else
            // 转化成字符串
            Json::Value root;
            root["x"] = _x;
            root["y"] = _y;
            root["oper"] = _oper;

            Json::FastWriter writer;
            *out = writer.write(root);
            return true;
#endif
        }
        bool Deserialize(const std::string &in)
        {
#ifdef SELFDEFINE
            auto left = in.find(SEP);
            if(left == std::string::npos) return false;
            auto right = in.rfind(SEP);
            if(right == std::string::npos) return false;

            _x = std::stoi(in.substr(0, left));
            _y = std::stoi(in.substr(right + SEP.size()));
            std::string oper = in.substr(left + SEP.size(), right - (left + SEP.size()));
            if(oper.size() != 1) return false;
            _oper = oper[0];
            return true;
#else
            Json::Value root;
            Json::Reader readr;
            bool res = readr.parse(in, root);
            if (!res)
                return false;

            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
            return true;
#endif
        }

    public:
        int _x;
        int _y;
        char _oper;
    };

    class Response
    {
    public:
        Response()
        {
        }
        Response(int result, int code)
            : _result(result), _code(code)
        {
        }
        bool Serialize(std::string *out)
        {
#ifdef SELFDEFINE
            *out = std::to_string(_result) + SEP + std::to_string(_code);
            return true;
#else
            // 转化成字符串
            Json::Value root;
            root["result"] = _result;
            root["code"] = _code;

            Json::FastWriter writer;
            *out = writer.write(root);
            return true;
#endif
        }
        bool Deserialize(const std::string &in)
        {
#ifdef SELFDEFINE
            auto pos = in.find(SEP);
            if(pos == std::string::npos) return false;
            _result = std::stoi(in.substr(0, pos));
            _code = std::stoi(in.substr(pos + SEP.size()));
            return true;
#else
            Json::Value root;
            Json::Reader readr;
            bool res = readr.parse(in, root);
            if (!res) return false;

            _result = root["result"].asInt();
            _code = root["code"].asInt();
            return true;
#endif
        }

    public:
        int _result; // 结果
        int _code;   // 0：succerss 1：除0 2：非法操作......
    };

    class Factory
    {
    public:
        Factory()
        {
            srand(time(nullptr) ^ getpid());
            opers = "+/*/%^&|";
        }
        std::shared_ptr<Request> BuildRequest()
        {
            int x = rand() % 10 + 1;
            usleep(x * 10);
            int y = rand() % 5; // [01,2,3,4]
            usleep(y * x * 5);
            char oper = opers[rand() % opers.size()];
            std::shared_ptr<Request> req = std::make_shared<Request>(x, y, oper);
            return req;
        }
        std::shared_ptr<Response> BuildResponse()
        {
            return std::make_shared<Response>();
        }
        ~Factory()
        {}

    private:
        std::string opers;
    };
}